<script setup>
import { ref, onMounted, computed } from 'vue'
import { UserProfileApi } from "@/api/new/userProfleApi.js"; // 正确引入UserProfileApi
import UserUtil from "@/utils/User/User.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { RoadDisasterApi } from '@/api/RoadDisasterApi.js'; // 保留用于更新和删除操作
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();
const activeIndex = ref('1') // 默认1
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(5)
const totalDisasters = ref(0)
const loading = ref(false)

// 灾害列表
const disasters = ref([])
const userId = computed(() => UserUtil.getUserId())

// 灾害状态映射 - 匹配后端 enum
const statusMap = {
  'unverified': '待证实',
  'verified': '已证实',
  'resolved': '已解决'
}

// 灾害类型映射 - 根据实际需要添加
const typeMap = {
  'earthquake': '地震',
  'flood': '洪水',
  'fire': '火灾',
  'landslide': '山体滑坡',
  'traffic_accident': '交通事故',
  'road_collapse': '道路塌方',
  'other': '其他',
  'landslid': '山体滑坡',
  'roadflooding': '内涝',
  'waterbody': '水体',
  'road_frozing': '路面结冰',
}

// 灾害状态标签样式 - 匹配后端 enum
const statusTagType = (status) => {
  switch(status) {
    case 'unverified': return 'warning';
    case 'verified': return 'primary';
    case 'resolved': return 'success';
    default: return 'info';
  }
}

// 灾害类型标签样式
const typeTagType = (type) => {
  switch(type) {
    case 'earthquake': return 'danger';
    case 'flood': return 'primary';
    case 'fire': return 'warning';
    case 'landslide': return 'info';
    case 'traffic_accident': return '';
    case 'road_collapse': return 'info';
    case 'landslid': return 'danger';
    case 'roadflooding': return 'warning';
    case 'waterbody': return 'info';
    case 'road_frozing': return 'success';
    default: return 'info';
  }
}

onMounted(() => {
  fetchDisasters();
})

// 获取并处理灾害列表 - 使用 UserProfileApi.getDisasters
const fetchDisasters = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    loading.value = true;
    // 使用 UserProfileApi.getDisasters 方法获取灾害数据
    // 将所有灾害查询修改为调用用户API
    const allDisastersData = await UserProfileApi.getDisasters(userId.value);
    console.log("UserProfileApi获取的灾害列表:", allDisastersData);
    
    // 确保数据是数组
    const disastersArray = Array.isArray(allDisastersData) ? allDisastersData : [];
    
    // 筛选数据 - 根据 activeTab
    let filteredData = disastersArray;
    if (activeTab.value !== 'all') {
        filteredData = disastersArray.filter(d => d.status === activeTab.value);
    }

    // 更新总数
    totalDisasters.value = filteredData.length;

    // 前端分页
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    disasters.value = filteredData.slice(startIndex, endIndex);

    console.log("处理后的灾害列表 (当前页):", disasters.value);

  } catch (error) {
    console.error('获取灾害列表失败:', error);
    ElMessage.error(`获取灾害列表失败: ${error.message}`);
    disasters.value = []; // 清空列表
    totalDisasters.value = 0;
  } finally {
    loading.value = false;
  }
}

// 查看灾害详情
const viewDisasterDetail = (disaster) => {
  if (!disaster || !disaster.disasterID) {
      ElMessage.warning('无法获取灾害ID');
      return;
  }
  router.push({
    name: 'platform.disasterDetail',
    params: { id: disaster.disasterID }
  });
}

// 编辑灾害 (跳转到编辑页)
const editDisaster = (disaster) => {
  if (!disaster || !disaster.disasterID) {
      ElMessage.warning('无法获取灾害ID');
      return;
  }
  router.push({
    name: 'platform.editDisaster',
    params: { id: disaster.disasterID }
  });
}

// 删除灾害
const deleteDisaster = (disaster) => {
  if (!disaster || !disaster.disasterID) {
      ElMessage.warning('无法获取灾害ID');
      return;
  }

  // 使用 disasterInfo 或 disasterType 作为标题的一部分
  const titleHint = disaster.disasterType ? typeMap[disaster.disasterType] || disaster.disasterType : (disaster.disasterInfo ? disaster.disasterInfo.substring(0, 10) + '...' : `ID ${disaster.disasterID}`);

  ElMessageBox.confirm(
    `确定要删除灾害 "${titleHint}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      loading.value = true;
      await RoadDisasterApi.deleteRoadDisaster(disaster.disasterID);
      ElMessage.success('删除成功');
      // 重新获取数据并应用筛选和分页
      fetchDisasters();
    } catch (error) {
      ElMessage.error(`删除失败: ${error.message}`);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 因为数据已在前端，只需重新计算当前页显示的数据
  fetchDisasters(); // 重新调用以应用分页
}

// 处理标签筛选
const handleTabChange = (tab) => {
  // activeTab 已通过 v-model 更新
  currentPage.value = 1; // 切换标签时重置到第一页
  fetchDisasters(); // 重新获取数据并应用筛选和分页
}

// 分享灾害信息
const shareDisaster = (disaster) => {
  if (!disaster || !disaster.disasterID) {
      ElMessage.warning('无法获取灾害ID');
      return;
  }
  // 假设前端展示灾害的路由是 /disaster/:id
  const shareUrl = `${window.location.origin}/disaster/${disaster.disasterID}`;
  
  navigator.clipboard.writeText(shareUrl).then(() => {
    ElMessage.success('链接已复制到剪贴板');
  }).catch(err => {
    console.error('复制失败:', err);
    ElMessage.error('复制链接失败');
  });
}

// 更新灾害状态
const changeDisasterStatus = async (disaster, newStatus) => {
    if (!disaster || !disaster.disasterID) {
        ElMessage.warning('无法获取灾害ID');
        return;
    }
    if (disaster.status === newStatus) {
        ElMessage.info('状态未改变');
        return;
    }

    ElMessageBox.confirm(
        `确定将灾害状态更改为 "${statusMap[newStatus]}" 吗？`,
        '状态更新确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(async () => {
        try {
            loading.value = true;
            // 调用RoadDisasterApi更新状态
            await RoadDisasterApi.updateDisasterStatus(disaster.disasterID, newStatus);
            ElMessage.success('状态更新成功');
            // 重新获取数据以反映更改
            fetchDisasters();
        } catch (error) {
            ElMessage.error(`状态更新失败: ${error.message}`);
        } finally {
            loading.value = false;
        }
    }).catch(() => {
        ElMessage.info('已取消状态更新');
    });
}

</script>

<template>
  <div class="disaster-manage-container">
    <div class="page-header">
      <h2>道路灾害管理</h2>
      <el-button type="primary" @click="router.push({name: 'platform.upload'})">上报新灾害</el-button>
    </div>

    <div class="filter-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="待证实" name="unverified"></el-tab-pane>
        <el-tab-pane label="已证实" name="verified"></el-tab-pane>
        <el-tab-pane label="已解决" name="resolved"></el-tab-pane>
      </el-tabs>
    </div>

    <el-card class="disaster-list" v-loading="loading">
      <template v-if="!loading && disasters.length === 0">
        <div class="empty-state">
          <el-empty description="暂无符合条件的灾害信息"></el-empty>
        </div>
      </template>

      <div v-else class="disaster-items">
        <!-- 使用 disasterID 作为 key -->
        <el-card v-for="disaster in disasters" :key="disaster.disasterID" class="disaster-item">
          <div class="disaster-header">
            <!-- 显示 disasterType 或 disasterInfo 作为标题 -->
            <h3 class="disaster-title" @click="viewDisasterDetail(disaster)">{{ typeMap[disaster.disasterType] || disaster.disasterType || disaster.disasterInfo.substring(0,20)+'...' || '未命名灾害' }}</h3>
            <div class="disaster-tags">
              <el-tag :type="typeTagType(disaster.disasterType)" size="small">{{ typeMap[disaster.disasterType] || disaster.disasterType || '未知类型' }}</el-tag>
              <el-tag :type="statusTagType(disaster.status)" size="small">{{ statusMap[disaster.status] || disaster.status || '未知状态' }}</el-tag>
            </div>
          </div>

          <div class="disaster-content">
            <div class="disaster-info">
              <!-- 显示 disasterInfo -->
              <p class="disaster-description">{{ disaster.disasterInfo || '无详细信息' }}</p>
              <div class="disaster-meta">
                <!-- 显示经纬度，可以考虑添加地图链接 -->
                <span><i class="el-icon-location"></i> 经度: {{ disaster.longitude.toFixed(4) }}, 纬度: {{ disaster.latitude.toFixed(4) }}</span>
              </div>
            </div>

            <!-- 媒体显示部分，将视频改为图片 -->
            <div class="disaster-media" v-if="disaster.video_url">
                <el-image 
                    style="width: 150px; height: 90px; object-fit: cover;"
                    :src="disaster.video_url" 
                    :preview-src-list="[disaster.video_url]"
                    fit="cover"
                />
            </div>
          </div>

        </el-card>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="totalDisasters > pageSize">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalDisasters"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="less">
/* 样式基本保持不变，根据需要微调 */
.disaster-manage-container {
  padding: 20px;
  width: 60%;
  max-width: 900px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  h2 { margin: 0; font-size: 24px; font-weight: 500; }
}

.filter-tabs { margin-bottom: 20px; }

.disaster-list {
  margin-bottom: 20px;
  .empty-state { padding: 40px 0; text-align: center; }
}

.disaster-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.disaster-item {
  border-radius: 8px;
  transition: box-shadow 0.3s ease; // 简化悬浮效果
  &:hover { box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08); }
}

.disaster-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  .disaster-title {
    margin: 0; font-size: 18px; font-weight: 500; cursor: pointer; color: #303133;
    &:hover { color: #409EFF; }
  }
  .disaster-tags { display: flex; gap: 8px; flex-shrink: 0; }
}

.disaster-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.disaster-info {
  flex: 1; min-width: 0;
  .disaster-description {
    margin: 0 0 10px; color: #606266; font-size: 14px; line-height: 1.5;
    display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3;
    overflow: hidden; word-break: break-all;
  }
  .disaster-meta {
    display: flex; flex-wrap: wrap; gap: 10px 15px;
    span {
      color: #909399; font-size: 13px; display: flex; align-items: center;
      i { margin-right: 4px; }
    }
  }
}

.disaster-media { // 用于显示视频或图片
    flex-shrink: 0;
}

.disaster-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  .el-button { padding: 8px 15px; }
  .el-dropdown { margin-right: 10px; } // 给下拉菜单一点间距
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 